#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmssl/sm2.h>
#include <gmssl/sm4.h>
#include <gmssl/rand.h>
#include <gmssl/error.h>


int main(void) {
    printf("=== Bob start ===\n");

    // 1. 检查/生成 SM2 密钥对
    FILE *fp_priv = fopen("bob_sm2.pem", "r");
    SM2_KEY bob_key;

    if (!fp_priv) {
        printf("Bob key not found — generating SM2 key pair...\n");
        sm2_key_generate(&bob_key);

        // ✅ 修正：GmSSL 3.1.1 只需要 3 个参数
        FILE *f1 = fopen("bob_sm2.pem", "w");
        sm2_private_key_info_encrypt_to_pem(&bob_key, "1234", f1);
        fclose(f1);

        FILE *f2 = fopen("bob_sm2_pub.pem", "w");
        sm2_public_key_info_to_pem(&bob_key, f2);
        fclose(f2);
        printf("✅ Bob SM2 keypair generated: bob_sm2.pem, bob_sm2_pub.pem\n");
    } else {
        sm2_private_key_info_decrypt_from_pem(&bob_key, "1234", fp_priv);
        fclose(fp_priv);
        printf("✅ Bob SM2 keypair loaded.\n");
    }

    // 2. 加载 Alice 公钥
    FILE *fp_apub = fopen("../alice/alice_sm2_pub.pem", "r");
    if (!fp_apub) {
        fprintf(stderr, "❌ 找不到 Alice 公钥文件 ../alice/alice_sm2_pub.pem\n");
        return -1;
    }
    SM2_KEY alice_pub;
    sm2_public_key_info_from_pem(&alice_pub, fp_apub);
    fclose(fp_apub);

    // 3. 准备明文
    const char *plaintext = "这是20231311wgq发送给20231325jlq的一条机密信息。";
    size_t msglen = strlen(plaintext);

    // 4. 生成随机 SM4 密钥与 IV
    unsigned char key[16], iv[16];
    rand_bytes(key, sizeof(key));
    rand_bytes(iv, sizeof(iv));

    // 5. 使用 SM4-CBC 加密
    size_t padded_len = ((msglen + 15) / 16) * 16;
    unsigned char *plain_padded = calloc(1, padded_len);
    unsigned char *cipher = calloc(1, padded_len);
    memcpy(plain_padded, plaintext, msglen);

    SM4_KEY sm4_ek;
    sm4_set_encrypt_key(&sm4_ek, key);
    sm4_cbc_encrypt(&sm4_ek, iv, plain_padded, padded_len / 16, cipher);

    FILE *f_cipher = fopen("ciphertext.bin", "wb");
    fwrite(cipher, 1, padded_len, f_cipher);
    fclose(f_cipher);

    // 6. SM2 加密 (数字信封 key+iv)
    unsigned char keyiv[32], ek[512];
    memcpy(keyiv, key, 16);
    memcpy(keyiv + 16, iv, 16);
    size_t eklen = sizeof(ek);

    if (sm2_encrypt(&alice_pub, keyiv, sizeof(keyiv), ek, &eklen) != 1) {
        fprintf(stderr, "❌ SM2 加密 key+iv 失败\n");
        return -1;
    }
    FILE *f_ek = fopen("ek.bin", "wb");
    fwrite(ek, 1, eklen, f_ek);
    fclose(f_ek);

    // 7. 签名 ciphertext
    unsigned char dgst[32];
    sm3_digest(cipher, padded_len, dgst); // SM2签名必须签摘要
    unsigned char sig[SM2_MAX_SIGNATURE_SIZE];
    size_t siglen = 0;

    if (sm2_sign(&bob_key, dgst, sig, &siglen) != 1) {
        fprintf(stderr, "❌ 签名失败\n");
        return -1;
    }
    FILE *f_sig = fopen("sig.bin", "wb");
    fwrite(sig, 1, siglen, f_sig);
    fclose(f_sig);

    printf("✅ Bob 加密与签名完成，生成文件：ciphertext.bin, ek.bin, sig.bin\n");
    printf("=== Bob done ===\n");

    free(plain_padded);
    free(cipher);
    return 0;
}
